﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Entities;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.RegionTypes.Create;

public class CreateRegionTypesCommandHandler : IRequestHandler<CreateRegionTypesCommandRequest, CreateRegionTypesCommandResponse>
{
    private readonly IMapper _mapper;
    private readonly IRegionTypeRepository _regionTypeRepository;

    public CreateRegionTypesCommandHandler(IMapper mapper, IRegionTypeRepository regionTypeRepository)
    {
        _mapper = mapper;
        _regionTypeRepository = regionTypeRepository;
    }

    public async Task<CreateRegionTypesCommandResponse> Handle(CreateRegionTypesCommandRequest request, CancellationToken cancellationToken)
    {
        var regionTypeExists = await _regionTypeRepository.AnyAsync(x => x.Name == request.Type, cancellationToken);
        if (regionTypeExists) throw new ConflictException("Тип региона с таким именем уже существует");

        var newRegionType = new RegionType();
        newRegionType.Name = request.Type;

        await _regionTypeRepository.InsertAsync(newRegionType, cancellationToken);
        return _mapper.Map<CreateRegionTypesCommandResponse>(newRegionType);
    }
}